//
//  XQBaseIdentityController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/9.
//

import UIKit

class XQBaseIdentityController: XQBaseController {

    var dataSource : [XQOrderDetailPersonWhereasModel] = [] {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    var jsonDic : [String : String] = [:]
    
    private lazy var bgImageView : UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "detail_publish_bg")
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
    private lazy var contentView : UIView = {
        let view = UIView()
        view.frame = CGRect(x: 15, y:UIDevice.xq_statusHeight() + 73, width: UIDevice.xq_width() - 30, height: UIDevice.xq_height() - UIDevice.xq_statusHeight() - 73)
        view.setRoundCorners([.topLeft,.topRight], radius: 16)
        view.backgroundColor = .white
        return view
    }()
    
    public lazy var tableView : UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = true
        tableView.register(XQBaseIdentityCell.self, forCellReuseIdentifier: "XQBaseIdentityCell")
        return tableView
    }()
    
    private lazy var bottomBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("Next", for: .normal)
        btn.backgroundColor = .mainTextColor
        btn.layer.cornerRadius = 30
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20,weight: .medium)
        btn.addTarget(self, action: #selector(bottomClick), for: .touchUpInside)
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        makeUI()
        makeConstraints()
        
        requestData()
        
        self.startTime = XQTimeTool.nowTime()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    @objc public func bottomClick() {}
    
    public func requestData() {}
    
    private func makeUI() {
        self.view.insertSubview(self.bgImageView, belowSubview: self.navigationBar)
        self.bgImageView.addSubview(self.contentView)
        self.contentView.addSubview(self.tableView)
        self.contentView.addSubview(self.bottomBtn)
    }
    
    private func makeConstraints() {
        self.bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.contentView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.xq_statusHeight() + 73)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.bottom.equalTo(0)
        }
        self.bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(32)
            make.right.equalTo(-32)
            make.height.equalTo(54)
            make.bottom.equalTo(-UIDevice.xq_safeTop() - 24)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(self.bottomBtn.snp.top).offset(-12)
        }
    }
    
    private func didAtIndexPath(indexPath : IndexPath) {
        self.view.endEditing(true)
        
        guard let model = currentModel(index: indexPath.section) else {return}
        
        if (model.twenty == "whitec") { // 城市
            showCityPop(model: model,indexPath: indexPath)
        }else {
            showDefaultPop(model: model,indexPath: indexPath)
        }
    }
    
    private func showCityPop(model : XQOrderDetailPersonWhereasModel,indexPath : IndexPath) {
        
        let k : String = model.object ?? ""
        
        var cityData = ""
        
        if (!jsonDic.isEmpty && !k.isEmpty) {            
            cityData = jsonDic[k]!
        }
            
        let contentView = XQBaseIdentityLocationPopView()
        contentView.frame = CGRect(x: 0, y:( UIDevice.xq_height() - 561) / 2, width: UIDevice.xq_width(), height: 561)
        contentView.sureHandle = {[weak self] (text) in
            guard let srongify = self else {return}
            XQHud.hidePop(controller: srongify)
            srongify.setDictAtIndexPath(text: text, indexPath: indexPath)
            srongify.tableView.reloadData()
        }
        contentView.cancelHandle = {
            XQHud.hidePop(controller: self)
        }
        
        XQHud.showPop(contentView,controller: self)
        if (!cityData.isEmpty) {
            contentView.selectLocation = cityData
        }
        
    }
    
    private func showDefaultPop(model : XQOrderDetailPersonWhereasModel,indexPath : IndexPath) {
        guard let thirdList = model.third else {return}
        
        var list : [String] = []
        if !thirdList.isEmpty {
            for m in thirdList {
                if let str = m.pardons {
                    list.append(str)
                }
            }
        }
        
        let contentView = XQBaseIdentityChoosePopView()
        contentView.frame = CGRect(x: 0, y:( UIDevice.xq_height() - 561) / 2, width: UIDevice.xq_width(), height: 561)
        contentView.sureHandle = {[weak self] (text) in
            guard let srongify = self else {return}
            XQHud.hidePop(controller: srongify)
            srongify.setDictAtIndexPath(text: text, indexPath: indexPath)
            srongify.tableView.reloadData()
        }
        contentView.cancelHandle = {
            XQHud.hidePop(controller: self)
        }

        XQHud.showPop(contentView,controller: self)
        contentView.dataSource = list
        contentView.selectData = getCellContent(indexPath: indexPath)
    }
    
    private func getCellContent(indexPath : IndexPath) -> String {
        
        if jsonDic.isEmpty {return ""}
            
        guard let model = currentModel(index: indexPath.section) else {return ""}
                
        guard let object : String = model.object else {return ""}
        
        if (object.isEmpty) {return ""}
        
        guard let value : String = jsonDic[object] else {return ""}
        
        if (value.isEmpty) {return ""}
        
        if (model.twenty == "whiteb" || model.twenty == "whitec") {
            return value
        }
        
        guard let thirdList = model.third else {return ""}
            
        var pardonsValue = ""
        if !thirdList.isEmpty {
            for m in thirdList {
                if (m.spectrophotometer == Int(value)) {
                    pardonsValue = m.pardons ?? ""
                    break
                }
            }
        }
        
        return pardonsValue
    }
    
    private func currentModel(index : Int) -> XQOrderDetailPersonWhereasModel? {
        if (index < dataSource.count) {
            return dataSource[index]
        }
        return nil
    }

}

extension XQBaseIdentityController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XQBaseIdentityCell", for: indexPath) as! XQBaseIdentityCell
        if let model = currentModel(index: indexPath.section) {
            cell.content = getCellContent(indexPath: indexPath)
            cell.placeHolder = model.possessing
            cell.textType = model.twenty
            cell.keyBoard = model.felonies == 1
        }
        cell.btnHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.didAtIndexPath(indexPath: indexPath)
        }
        cell.textFielHandle = {[weak self] (text) in
            guard let srongify = self else {return}
            srongify.setDictAtIndexPath(text: text, indexPath: indexPath)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = XQBaseIdentityHeaderView()
        if let model = currentModel(index: section) {
            headerView.content = model.accessing
        }
       
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 48
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView()
        return footerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

extension XQBaseIdentityController {
    
    public func updateJsonDic(list : [XQOrderDetailPersonWhereasModel]) {
        for model in list {
            let k : String = model.object ?? ""
            let v : String = model.pardon ?? ""
            if !k.isEmpty {
                if (model.twenty == "whitea") {
                    let idValue : String = getSpacemobile(v: v,list: model.third)
                    self.jsonDic[k] = idValue
                }else {
                    self.jsonDic[k] = v
                }
            }
        }
    }
    
    public func notifyRisk(numberType : String) {
        endTime = XQTimeTool.nowTime()
        
        XQAnalysisManager.shared.notifyRisk(numberType: numberType, longitude: self.longitude, latitude: self.latitude, startT: self.startTime, endT: self.endTime, orderId: "")
    }
    
    private func setDictAtIndexPath(text : String,indexPath : IndexPath) {
        guard let model = currentModel(index: indexPath.section) else {return}
        guard let object : String = model.object else {return}
        if (object.isEmpty) {return}
        
        let idValue : String = getSpacemobile(v: text,list: model.third)
        
        if (model.twenty == "whiteb" || model.twenty == "whitec") {
            jsonDic[object] = text
        }else {
            jsonDic[object] = idValue
        }
    }
    
    private func getSpacemobile(v : String,list : [XQOrderDetailPersonThirdModel]?) -> String {
        var spacemobile : String = ""
        
        guard let datas = list else {return ""}
        
        for model in datas {
            if model.pardons == v,let spec = model.spectrophotometer{
                spacemobile = "\(spec)"
            }
        }
        return spacemobile
    }
    
}
